package cn.edu.zstu.qingzhu.qingzhushop.rabbitmq.publisher;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * FileName: BasicPublisher
 *
 * @Author: LvYibin
 * @Date: 2020/7/18 11:49
 * @Description:基本生产者模型
 */
@Component
public class BasicPublisher {
//    private static final Logger log = LoggerFactory.getLogger(BasicPublisher.class);
//    @Autowired
//    private ObjectMapper objectMapper;
//    @Autowired
//    private RabbitTemplate rabbitTemplate;
//    @Autowired
//    private Environment env;
//    /**发送消息
//     * @Param message 待发送的消息，即一字符串
//     * */
//    public void sendMsg(String message){
//        if(!Strings.isEmpty(message)){
//            try {
//                rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
//                rabbitTemplate.setExchange(env.getProperty("mq.basic.info.exchange.name"));
//                rabbitTemplate.setRoutingKey(env.getProperty("mq.basic.info.routing.key.name"));
//                Message msg = MessageBuilder.withBody(message.getBytes("utf-8")).build();
//                rabbitTemplate.convertAndSend(msg);
//                log.info("基本消息模型-生产者-发送消息：{} ",message);
//            }catch (Exception e){
//                log.error("基本消息模型-生产者-发送消息发生异常：{} ",message,e.fillInStackTrace());
//            }
//        }
//    }
private static final Logger log= LoggerFactory.getLogger(BasicPublisher.class);

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private Environment env;


    /**
     * 发送消息
     * @param message
     */
    public void sendMsg(String message){

            try {
                //rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
                Message msg = MessageBuilder.withBody(message.getBytes(StandardCharsets.UTF_8)).setDeliveryMode(
                        MessageDeliveryMode.PERSISTENT).build();
                rabbitTemplate.convertAndSend("exchange1","routing:key:1",msg);
                log.info("基本消息模型-生产者-发送消息：{} ",message);
            }catch (Exception e){
                log.error("基本消息模型-生产者-发送消息发生异常：{} ",message,e.fillInStackTrace());
            }

    }
}
